<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="昵称 " prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入昵称 "
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="账号" prop="account">
        <el-input
          v-model="queryParams.account"
          placeholder="请输入账号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="queryParams.email"
          placeholder="请输入邮箱"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['kaifa:user:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['kaifa:user:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['kaifa:user:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['kaifa:user:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="昵称 " align="center" prop="name"/>
      <el-table-column label="账号" align="center" prop="account"/>
      <el-table-column label="邮箱" align="center" prop="email"/>
      <el-table-column label="手机号" align="center" prop="phone"/>
      <el-table-column label="密码" align="center" prop="password"/>
      <el-table-column label="头像" align="center" prop="avatar" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.avatar" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="简介" align="center" prop="intro"/>
      <el-table-column label="性别" align="center" prop="sex">
        <template slot-scope="scope">
          <span>{{ scope.row.sex === 0 ? "保密" : scope.row.sex === 1 ? "男" : "女" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="出生日期" align="center" prop="birthday" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.birthday, '{y}年{m}月{d}日') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标签数组" align="center" prop="birthday">
        <template slot-scope="scope">

          <el-tag
            type="warning"
            v-for="(item, index) in scope.row.tags.split(',')"
            :key="index">
            {{ findTagName(item) }}
          </el-tag>

        </template>
      </el-table-column>

      <el-table-column label="实名信息" align="center" prop="birthday" width="180">
        <template slot-scope="scope">
          <p v-if="scope.row.aStanding === null">
            没有实名认证
          </p>
          <p v-else>
            <el-tag>{{ scope.row.aStanding.name }}，信用分：{{ scope.row.aStanding.credit }}</el-tag>
            <el-tag type="success">{{ scope.row.aStanding.number }}</el-tag>
          </p>

        </template>
      </el-table-column>


      <el-table-column label="登录密钥" align="center" prop="secret"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}年{m}月{d}日{h}时{i}分{s}秒') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}年{m}月{d}日{h}时{i}分{s}秒') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="注册ip" align="center" prop="createIp"/>
      <el-table-column label="修改ip" align="center" prop="updateIp"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['kaifa:user:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['kaifa:user:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="昵称 " prop="name">
          <el-input v-model="form.name" placeholder="请输入昵称 "/>
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="form.account" placeholder="请输入账号"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <image-upload v-model="form.avatar"/>
        </el-form-item>


        <el-form-item label="身份信息">
          <el-select
            v-model="form.standingId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入名称"
            :remote-method="selectStanding"
            :loading="standing.loading">
            <el-option
              v-for="(item,index) in standing.list"
              :key="index"
              :label="item.name+'-'+item.number"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="性别">
          <el-select v-model="form.sex" :min-height="192">
            <el-option
              label="保密"
              :value="0">
            </el-option>
            <el-option
              label="男"
              :value="1">
            </el-option>
            <el-option
              label="女"
              :value="2">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="简介">
          <editor v-model="form.intro" :min-height="192"/>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker clearable
                          v-model="form.birthday"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择出生日期">
          </el-date-picker>
        </el-form-item>


        <el-form-item label="标签">
          <el-select
            style="width: 100%"
            v-model="form.tags"
            multiple
            filterable
            remote
            reserve-keyword
            placeholder="请输入名称"
            :remote-method="selectTags"
            :loading="tags.loading">
            <el-option
              v-for="(item,index) in tags.list"
              :key="index"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="登录密钥" prop="secret">
          <el-input v-model="form.secret" placeholder="请输入登录密钥"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listUser, getUser, delUser, addUser, updateUser} from "@/api/kaifa/user";
import {getStandingByName} from "@/api/kaifa/standing";
import {getShowTag, getTagsByName} from "@/api/kaifa/tag";

export default {
  name: "User",
  data() {
    return {
      standing: {
        list: [],
        loading: false
      },
      tags: {
        list: [],
        showList: [],
        loading: false
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        account: null,
        email: null,
        phone: null,
        standingId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
        // 使用 forEach 遍历数组


        let getTags = "";
        this.userList.forEach((user) => {
          if (getTags !== "") {
            getTags += "," + user.tags
          } else {
            getTags += user.tags
          }
        });

        getShowTag([...new Set(getTags.split(","))]).then(response => {
          this.tags.showList = response.rows;
          this.tags.list = response.rows;
        });


      });


    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        account: null,
        email: null,
        phone: null,
        password: null,
        avatar: null,
        intro: null,
        sex: null,
        birthday: null,
        tags: null,
        standingId: null,
        secret: null,
        createTime: null,
        updateTime: null,
        createIp: null,
        updateIp: null,
        isDelete: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户";
    },


    /** 远程查询标签信息*/
    selectStanding(name) {
      if (name !== '') {
        this.standing.loading = true;
        getStandingByName(name).then(response => {
          this.standing.list = response.rows
          this.standing.loading = false;
        })
      } else {
        this.standing.list = []
      }
    },
    /** 远程查询身份信息*/
    selectTags(name) {
      if (name !== '') {
        this.tags.loading = true;
        getTagsByName(name).then(response => {
          this.tags.list = response.rows;
          this.tags.loading = false;

        })
      } else {
        this.tags.list = []
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getUser(id).then(response => {
        this.form = response.data;
        this.form.tags = this.form.tags.split(",")
        this.open = true;
        this.title = "修改用户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.tags = this.form.tags.join(",")
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除用户编号为"' + ids + '"的数据项？').then(function () {
        return delUser(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('kaifa/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    /**处理标签匹配模式*/

    findTagName(item) {
      // 在 tags.showList 中查找对应 id 的对象
      const tag = this.tags.showList.find(i => i.id === item);
      // 如果找到则返回 name，否则返回空字符串
      return tag ? tag.name : '';
    }
  }
};
</script>
